﻿using System.Data;
using System.Data.SqlClient;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using VirtualTournaments.Business.Tournaments;
using VirtualTournaments.DataAccess;
using VirtualTournaments.DataAccess.EntityManagers;

namespace VirtualTournaments.Business.Tests.ServicesTests
{
	[TestClass]
	public class TournamentsTest2
	{
		[ClassInitialize()]
		public static void MyClassInitialize(TestContext testContext) { }
		
		[ClassCleanup()]
		public static void MyClassCleanup() { }

		SqlConnection connection;
		[TestInitialize()]
		public void MyTestInitialize()
		{
			connection = DataAccess.SqlServer.Connections.ConnectionManager.GetConnection() as SqlConnection;
			connection.Open();
			DeleteAll(connection);
		}
		
		[TestCleanup()]
		public void MyTestCleanup()
		{
			DeleteAll(connection);
			connection.Close();
		}

		//[TestMethod]
		[TestMethod, Ignore]
		public void TournamentLoadThenSaveBugTest()
		{ 
			// Simplemente crea un torneo, y luego lo guarda sin hacerle modificacion alguna, deberia quedar todo como antes.
			 
			ITournamentsManager dataManager = DataAccessManager.EntityManagersFactory.GetTournamentsManager();
			Team[] teams = new Team[] { new Team("Boca"), new Team("River"), new Team("Vélez"), new Team("Banfield"), new Team("Independiente"), new Team("Racing") };
			
			//creo un torneo y lo guardo en la base
			dataManager.Save(new VirtualTournaments.Business.Tournaments.AllAgainstAllTournament("Apertura", teams));
			//lo obtengo
			Business.Tournaments.Tournament bizTournament = dataManager.GetByExactName("Apertura");
			//sin modificarlo lo guardo
			dataManager.Save(bizTournament); //error aquí: An attempt was made to remove a relationship between a Tournament and a Standing. However, one of the relationship's foreign keys (Standing.TournamentId) cannot be set to null..
		}

		private static void DeleteAll(SqlConnection connection)
		{
			ExecuteSql(connection, @"DELETE FROM BetsTargetsBets;");
			ExecuteSql(connection, @"DELETE FROM ThreeWaysBetsTargets;");
			ExecuteSql(connection, @"DELETE FROM TournamentPodiumBetsTargets;");
			ExecuteSql(connection, @"DELETE FROM BetsTargets;");
			ExecuteSql(connection, @"DELETE FROM BetsTypes;");
			ExecuteSql(connection, @"DELETE FROM JourneysMatches;");
			ExecuteSql(connection, @"DELETE FROM Matches;");
			ExecuteSql(connection, @"DELETE FROM Standings;");
			ExecuteSql(connection, @"DELETE FROM Tournaments;");
		}

		private static void ExecuteSql(SqlConnection connection, string sql)
		{
			using (SqlCommand command = connection.CreateCommand())
			{
				command.CommandType = CommandType.Text;
				command.CommandText = sql;
				command.ExecuteNonQuery();
			}
		}
	}
}
